﻿using System.Diagnostics.CodeAnalysis;
using System.Windows;
using System.Windows.Controls;
using Pfz.DataTypes;
using Pfz.Factoring;

namespace Pfz.WpfControls.ValueControls
{
	[SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")]
	[AutoRegisterInControlFactory(typeof(bool))]
	internal class BooleanControl:
		UserControl,
		IHasDisplayName,
		IValueControl,
		IHasValueChanged
	{
		protected CheckBox _checkBox = new CheckBox();
		
		/// <summary>
		/// Creates a new boolean control instance.
		/// </summary>
		public BooleanControl()
		{
			HorizontalAlignment = HorizontalAlignment.Center;
			VerticalAlignment = VerticalAlignment.Center;
			Content = _checkBox;
		}
	
		private string _displayName;
		
		/// <summary>
		/// Gets or sets the DisplayName of this control.
		/// </summary>
		public string DisplayName
		{
			get
			{
				return _displayName;
			}
			set
			{
				_checkBox.Content = value;
				_displayName = value;
				
				if (value == null)
					HorizontalAlignment = HorizontalAlignment.Center;
				else
					HorizontalAlignment = HorizontalAlignment.Left;
			}
		}
		
		#region IDataControl Members
			/// <summary>
			/// Sets the IsChecked to null.
			/// </summary>
			public void Clear()
			{
				_checkBox.IsChecked = null;
			}
			
			/// <summary>
			/// Gets or sets a value indicating if this control is/should be
			/// read-only.
			/// </summary>
			public bool IsReadOnly
			{
				get
				{
					return !IsEnabled;
				}
				set
				{
					IsEnabled = !value;
				}
			}
		#endregion
		#region IValueContainer Members
			object IValueContainer.Value
			{
				get
				{
					return _checkBox.IsChecked;
				}
				set
				{
					_checkBox.IsChecked = (bool?)value;
				}
			}
		#endregion
		#region IHasValueChanged Members
			event RoutedEventHandler IHasValueChanged.ValueChanged
			{
				add
				{
					_checkBox.Checked += value;
					_checkBox.Unchecked += value;
				}
				remove
				{
					_checkBox.Checked -= value;
					_checkBox.Unchecked -= value;
				}
			}
		#endregion
	}

	[SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")]
	[AutoRegisterInControlFactory(typeof(bool?))]
	internal sealed class BooleanControl2:
		BooleanControl
	{
		public BooleanControl2()
		{
			_checkBox.IsThreeState = true;
		}
	}
}
